package cn.imvc.app.models;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.entities.FundFlow;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.FundFlowRepository;
import cn.imvc.data.domain.ViewRequest;
import cn.imvc.util.AES;

@Service
public class FundFlowModelImpl implements FundFlowModel{
	
	@Autowired
	private FundFlowRepository fundFlowRepository;
	@Autowired
	private SystemConfig systemConfig;
	
	public void saveFundFlow(Member member,Integer money,String code,Byte type){
		if (money==0){
			return;
		}
		FundFlow fundFlow=new FundFlow();
		fundFlow.setAccount(member.getAccount());
		fundFlow.setMember(member);
		fundFlow.setCode(code);
		fundFlow.setType(type);
		Calendar cal=Calendar.getInstance();
		cal.get(Calendar.YEAR);
		fundFlow.setYear(cal.get(Calendar.YEAR));
		fundFlow.setMonth(cal.get(Calendar.MONTH)+1);
		fundFlow.setDay(cal.get(Calendar.DATE));
		fundFlow.setSigned(money>=0?"+":"-");
		fundFlow.setMoney(Math.abs(money));
		fundFlow.setAmount(money);
		fundFlow.setCreatedAt(new Date());
		fundFlow.setUpdatedAt(new Date());
		fundFlow.setFromMember(member);
		fundFlow.setVerify(AES.encrypt(money+"",systemConfig.getAESPassword()));
		fundFlowRepository.save(fundFlow);
	}
	
	public void saveFundFlow(Member member,Integer money,String code,Byte type,Member fromMember){
		if (money==0){
			return;
		}
		FundFlow fundFlow=new FundFlow();
		fundFlow.setAccount(member.getAccount());
		fundFlow.setMember(member);
		fundFlow.setCode(code);
		fundFlow.setType(type);
		Calendar cal=Calendar.getInstance();
		cal.get(Calendar.YEAR);
		fundFlow.setYear(cal.get(Calendar.YEAR));
		fundFlow.setMonth(cal.get(Calendar.MONTH)+1);
		fundFlow.setDay(cal.get(Calendar.DATE));
		fundFlow.setSigned(money>=0?"+":"-");
		fundFlow.setMoney(Math.abs(money));
		fundFlow.setAmount(money);
		fundFlow.setCreatedAt(new Date());
		fundFlow.setUpdatedAt(new Date());
		fundFlow.setFromMember(fromMember);
		fundFlow.setVerify(AES.encrypt(money+"",systemConfig.getAESPassword()));
		fundFlowRepository.save(fundFlow);
	}

	public Page<FundFlow> findAll(ViewRequest viewRequest) {
	
		return fundFlowRepository.findAll("distinct f","FundFlow f left join f.member as m",viewRequest);
	}

	public Page<FundFlow> findAllByMemberId(ViewRequest viewRequest, int memberId) {
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		viewRequest.getParams().put("_and_f_dot_member_dot_id_eq_number", memberId+"");
		viewRequest.getSort().put("createdAt", "DESC");
		return fundFlowRepository.findAll("f","FundFlow f",viewRequest);
	}


}
